﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ComicQ.Controller;
using ComicQ.Domain.Table;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for ComicStatusView.xaml
    /// </summary>
    public partial class ComicStatusView
    {
        private readonly ComicStatusController _comicStatusControl;
        private IList<ComicStatus> _comicStatuses;

        public ComicStatusView()
        {
            InitializeComponent();

            _comicStatusControl = new ComicStatusController();
            _comicStatuses = _comicStatusControl.GetAllComicStatus();
            dataGridComicStatus.ItemsSource = _comicStatuses;
        }

        private void RefreshGrid()
        {
            dataGridComicStatus.ItemsSource = null;
            _comicStatuses = _comicStatusControl.GetAllComicStatus();
            dataGridComicStatus.ItemsSource = _comicStatuses;
        }

        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var newWindow = new ComicStatusEditorView();

            if (newWindow.ShowDialog() != false)
            {
            }
            else
            {
                RefreshGrid();
            }
        }

        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridComicStatus.SelectedItem == null)
                    throw new NullReferenceException();

                var comicStatus = _comicStatuses
                        .Where(a => a.Id == _comicStatuses[dataGridComicStatus.SelectedIndex].Id)
                        .Select(a => a)
                        .Single();

                _comicStatusControl.DeleteComicStatus(comicStatus);
                MessageBox.Show("sukses menghapus comic status");
                RefreshGrid();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau didelete");
            }
        }

        private void ButtonEditClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridComicStatus.SelectedItem == null)
                    throw new NullReferenceException();

                var newWindow = new ComicStatusEditorView(_comicStatuses[dataGridComicStatus.SelectedIndex]);

                if (newWindow.ShowDialog() != false)
                {
                }
                else
                {
                    RefreshGrid();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau diedit");
            }
        }
    }
}
